package com.wxassistant.component.wechat;

import cn.zhouyafeng.itchat4j.beans.BaseMsg;
import cn.zhouyafeng.itchat4j.core.Core;
import cn.zhouyafeng.itchat4j.utils.MyHttpClient;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.util.EntityUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.logging.Logger;

/**
 * Created by huangzihao on 2017/12/15.
 */
public class TulingRobotHandler {
    static Logger logger = Logger.getLogger("TulingRobot");
    static MyHttpClient myHttpClient = Core.getInstance().getMyHttpClient();
    static final String url = "http://www.tuling123.com/openapi/api";
    static final String apiKey = "99ae9839ba074c88ba6fd2f90c2d54dc"; // 这里是我申请的图灵机器人API接口，每天只能1000次调用)

    public static String reply(BaseMsg msg) {
        String result = "";
        String text = msg.getText();
        Map<String, String> paramMap = new HashMap<String, String>();
        paramMap.put("key", apiKey);
        paramMap.put("info", text);
        paramMap.put("userid", msg.getFromUserName().substring(0, 31));
        String paramStr = JSON.toJSONString(paramMap);
        try {
            HttpEntity entity = myHttpClient.doPost(url, paramStr);
            String tulingResult = EntityUtils.toString(entity, "UTF-8");
            JSONObject obj = JSON.parseObject(tulingResult);
            String resultCode = obj.getString("code");
            if (resultCode.equals("100000")) {
                result = obj.getString("text");
            } else if (resultCode.equals("200000")) {
                result = "你看看这个: "+obj.getString("url");
            } else if (resultCode.equals("302000")) {
                JSONArray list = obj.getJSONArray("list");
                if (list.size() > 0) {
                    result = "你看看这个: ";
                    for (int i = 0; i < list.size(); i++) {
                        JSONObject item = list.getJSONObject(i);
                        result += "\n"+item.get("article")+"\n"+item.get("detailurl")+"\n\n";
                    }
                } else {
                  result = "没找到内容";
                }
            }
        } catch (Exception e) {
            logger.info(e.getMessage());
        }
        return result;
    }
}
